angular.module("m",[])
    .controller("c",function ($scope,$interval) {
        /**定义基本信息**/
        /**发给谁**/
        $scope.toUser = ["test02","test03","test04","user001","zzk-001"];
        $scope.toLTUser = [];//用于联调
        $scope.passes = ["de943cef53f21866f463c65cda8d92c5","42028a1f1d2c6b370886bf677b6442b2",
            "1afc09c94f1888223ae82930af04bb78","971711e53709182de4af4f168f375e27",
            "0f02608965bd884473a6a75ed95a2563","79a5dd2e98a91712a0e0d1e670b0c384",
            "e2fb35b52f3cfbffc38b4ad9b7f2f707","597ce608dcd5c05a21c67c57efa90099",
            "29162314a0883a6e881fb3706d6081d9","8643c9b82602946e81f2977e9783677e"];
        $scope.msgList = [];
        (function () {
            for(var i=1;i<11;i++){
                $scope.toLTUser.push({
                    accid:"lt-0"+(i<10?"0"+i:i),
                    token:$scope.passes[i-1]});
            }
        })();
        console.log($scope.toLTUser);
        $scope.infoObj = {
            appKey:"ab1c052dadc6f45709f55bdd7cb0c347",
            userOne:{
                accid:"1",
                token:"21d99e08ea67b1049995f0dff059d9d3",
                text:"",
                to:$scope.toUser[0]//默认发给用户2
            }
        };
        /**初始化云信sdk**/
        //用户1
        $scope.configObj = {
            appKey: $scope.infoObj.appKey,
            account: $scope.infoObj.userOne.accid,
            token: $scope.infoObj.userOne.token,
            onconnect: function () {
                console.log('登录成功');
                //$scope.qualityImage();
            },
            onwillreconnect: function (obj) {
                console.log('即将重连');
                console.log(obj.retryCount);
                console.log(obj.duration);
            },
            ondisconnect: function (error) {
                console.log('丢失连接');
                console.log(error);
                if (error) {
                    switch (error.code) {
                        // 账号或者密码错误, 请跳转到登录页面并提示错误
                        case 302:
                            break;
                        // 重复登录, 已经在其它端登录了, 请跳转到登录页面并提示错误
                        case 417:
                            break;
                        // 被踢, 请提示错误后跳转到登录页面
                        case 'kicked':
                            break;
                        default:
                            break;
                    }
                }
            },
            onerror: function (error) {
                console.log(error);
            },
            /**收到消息**/
            onmsg: function(msg) {
                console.log('收到消息', msg.scene, msg.type, msg);
                $scope.$apply(function () {
                    $scope.msgList.push(msg);
                    $scope.scrollToBottom("msgDivId");
                });
                switch (msg.type) {
                    case 'custom':
                        break;
                    case 'notification':
                        // 处理群通知消息
                        break;
                    default:
                        break;
                }
            },
            onroamingmsgs: function(obj) {
                console.log('收到漫游消息', obj);
            },
            onofflinemsgs: function(obj) {
                console.log('收到离线消息', obj);
                $scope.$apply(function () {
                    for(var i in obj.msgs){
                        $scope.msgList.push(obj.msgs[i]);
                        $scope.scrollToBottom("msgDivId");
                    }
                });
            }
        };
        $scope.nimOne = NIM.getInstance($scope.configObj);
        $scope.loginStatus = "在线";
        //登录
        $scope.login = function () {
            $scope.nimOne.connect();
            $scope.loginStatus = "在线";
        };
        //注销
        $scope.logout = function () {
            $scope.nimOne.disconnect();
            $scope.loginStatus = "离线";
        };
        /**发送消息**/
        $scope.preSend = function () {
            if($scope.infoObj.userOne.text==""||$scope.infoObj.userOne.text==null){
                return ;
            }
            $scope.sendText($scope.nimOne,{
                to:$scope.infoObj.userOne.to,
                text:$scope.infoObj.userOne.text
            });
        };
        $scope.sendText = function (nim,obj) {
            nim.sendText({
                scene: 'p2p',
                to: obj.to,
                text: obj.text,
                custom: JSON.stringify({"custom":"自定义消息用custom字段发普通文本"}),
                type: 'custom',
                done: function(error, msg) {
                    console.log(error);
                    console.log(msg);
                    console.log('发送' + msg.scene + ' ' + msg.type + '消息' + (!error?'成功':'失败') + ', id=' + msg.idClient);
                    $scope.$apply(function () {
                        $scope.msgList.push(msg);
                        $scope.scrollToBottom("msgDivId");
                    });
                }
            });
        };
        /**发送图片**/
        sendImg = function (file) {
            var nim = $scope.nimOne;
            var ctime = (new Date()).valueOf().toString();//做个标记方便替换
            console.log("ctime: "+ctime);
            //压缩完后就push到消息列表,方便快速显示
            $scope.$apply(function () {
                $scope.msgList.push({ctime:ctime,file:file,type:"image"});
                $scope.scrollToBottom("msgDivId");
            });
            nim.sendFile({
                scene: 'p2p',
                to: $scope.infoObj.userOne.to,
                //file: file,
                dataURL:file.url,
                type:"image",
                done: function(error, msg) {
                    console.log(msg);
                    console.log('发送' + msg.scene + ' ' + msg.type + '消息' + (!error?'成功':'失败') + ', id=' + msg.idClient);
                    $scope.$apply(function () {
                        $('#fileUpload').val('');//发送成功后清除input标签的内容,防止再次选择相同的文件,不能出发changeInput方法
                        for(var i=$scope.msgList.length-1;i>-1;i--){//把之前本地缓存那个替换成真实的
                            console.log($scope.msgList);
                            if($scope.msgList[i].ctime&&$scope.msgList[i].ctime===ctime){
                                var tempI = i;
                                var tImg = new Image();
                                tImg.onload = function () {//等图片全部加载完后再复制,防止出现渐进效果,影响体验
                                    $scope.msgList[tempI]=msg;//这里是异步操作,就要用缓存的那个i -> tempI
                                };
                                tImg.src = msg.file.url;
                                break ;
                            }
                        }
                        $scope.scrollToBottom("msgDivId");
                    });
                }
            });
        };
        $scope.imgClick = function (url) {
            //目标全屏元素
            var target = $(".popup");
            //如果存在,直接赋值并显示
            if(target.length!==0){
                target.children().children().attr("src",url);
                target.css("display", "block");
                return ;
            }
            //如果不存在,即为第一次加载,生成DOM元素即可
            var div = $(".fullScreen");
            var t = $('<div class="popup"><div class="popup-bg"><img alt=""/></div></div>');
            div.append(t);//添加到html文档中
            div.children().children().children().attr("src",url);
            div.click(function () {
                $(".popup").css("display", "none");
            });
            div.children().css("display", "block");
        };
        /**JS图片压缩（pc端和移动端都适用）**/
        function dealImage(path, obj, callback){
            var img = new Image();
            img.src = path;
            img.onload = function(){
                var that = this;
                // 默认按比例压缩
                var w = that.width,
                    h = that.height,
                    scale = w / h;
                w = obj.width || w;
                h = obj.height || (w / scale);
                var quality = 0.7;  // 默认图片质量为0.7
                //生成canvas
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                // 创建属性节点
                var anw = document.createAttribute("width");
                anw.nodeValue = w;
                var anh = document.createAttribute("height");
                anh.nodeValue = h;
                canvas.setAttributeNode(anw);
                canvas.setAttributeNode(anh);
                ctx.drawImage(that, 0, 0, w, h);
                // 图像质量
                if(obj.quality && obj.quality <= 1 && obj.quality > 0){
                    quality = obj.quality;
                }
                // quality值越小，所绘制出的图像越模糊
                var base64 = canvas.toDataURL('image/jpeg', quality);
                // 回调函数返回base64的值
                callback(base64);
            }
        }
        changeInput = function () {
            //获取文件
            var file = document.getElementById("fileUpload").files[0];
            if(file===undefined){
                return ;
            }
            //创建读取文件的对象
            var reader = new FileReader();
            //创建文件读取相关的变量
            var imgFile;
            //为文件读取成功设置事件
            reader.onload=function(e) {
                console.log('文件读取完成');
                imgFile = e.target.result;//base64
                //console.log(imgFile);
                $("#imgContent-yuan").attr('src', imgFile);//原图
                dealImage(imgFile,{
                    quality:0.7
                },function (imgFile) {
                    $("#imgContent").attr('src', imgFile);//压缩图
                    var file = {url:imgFile};
                    sendImg(file);
                });
            };
            //正式读取文件
            reader.readAsDataURL(file);
        };
        //div内容变化时滚动条始终在最底部
        $scope.scrollToBottom = function (divId) {
            var div = document.getElementById(divId);
            $interval(function () {
                div.scrollTop = div.scrollHeight;
            },120,6);
        };
    });
